import gaev
from gaev import HumanizeContext
from gaev.actions import *


class IndexAction(TemplateAction):
	template='base_index.html'
	humanize_context=HumanizeContext(use_html=True)

	def get_param_defaults(self):
		defaults={
				'page': 0,
				'page_size': 20,
				}
		return defaults

	def get_pagination(self, total_count):
		page_index=self.params['page']
		page_size=self.params['page_size']
		page_count=max([1,utils.ceil(total_count*1.0/page_size)])
		if page_count==1:
			return None
		res=[]
		for i in range(0,page_count):
			if i==page_index:
				res.append((i+1, None))
			else:
				res.append( (i+1, self.get_url({'page':i})) )
		return res
	
	def perform_template(self):
		entity_set=self.object
		model=entity_set.model
		page_index=self.params['page']
		page_size=self.params['page_size']
		
		cols=model.get_columns()
		captions=model.get_column_captions(cols)
		
		query=entity_set.all()
		query.order(model.get_default_ordering())
		
		entities=query.fetch(page_size, page_index*page_size)
		total_count=query.count(1000)

		rows=[]
		for entity in entities:
			row=entity.get_humanized_properties(self.humanize_context)
			row['actions']=get_actions_details(entity)
			rows.append(row)
			
		entity_set_actions=get_actions_details(entity_set)
		entity_set_actions=utils.filter(lambda x:x['name']!='index', entity_set_actions)

		pagination=self.get_pagination(total_count)
			
		params={
			'rows':rows, 
			'cols':cols, 
			'captions': captions,
			'pagination': pagination,
			'entity_set_actions': entity_set_actions
			}
		return params

def GetInAction(object=None, request=None, **kwargs):
	from gaev.model.restrictor import ReferenceRestrictor
	model=object.__class__
	if not model._inner_property:
		raise gaev.Error()
	target_prop=model._inner_property
	restrictor=ReferenceRestrictor(target_prop.model_class.entities(), target_prop, object)
	entity_set=restrictor.get_restricted_entity_set()
	res=IndexAction(entity_set, request=request, **kwargs)
	res.image_url='/static/images/icon_folder.gif'
	return res
		
class DeleteAllAction(GetPostAction):
	template='base_question.html'
	def get_template_params(self):
		model=self.object.model
		return {
			'question': 'Do you really want to delete all records in table %s?' % model.__name__,
			'options': [('yes', 'Yes'), ('no', 'No')]
			}
	def success(self):
		entity_set=self.object
		if self.request.POST.has_key('yes'):
			for obj in entity_set.all():
				obj.delete()

class DeleteAction(GetPostAction):
	image_url='/static/images/icon_delete.gif'
	template='base_question.html'
	def get_template_params(self):
		entity=self.object
		model=entity.__class__
		params={'options': [('yes', 'Yes'), ('no', 'No')]}
		if model.get_human_key():
			#if model has a human key, the entity has reasonable caption
			capt=entity.get_caption()
			params['question']='Do you really want to delete entity %s?' % capt
		else:
			params['question']='Do you really want to delete selected entity?'
		return params
	def success(self):
		entity=self.object
		if self.request.POST.has_key('yes'):
			entity.delete()

		
class AddAction(FormAction):
	template='base_edit.html'
	def create_form(self):
		model=self.object
		if self.request.method == 'POST':
			return forms.ModelForm(model=model,data=self.request.POST)
		else:
			return forms.ModelForm(model=model)
	def success(self):
		form=self.get_form()
		form.save()
		
class EditAction(FormAction):
	image_url='/static/images/icon_edit.gif'
	template='base_edit.html'
	def create_form(self):
		entity=self.object
		if self.request.method == 'POST':
			return forms.ModelForm(entity=entity,data=self.request.POST)
		else:
			return forms.ModelForm(entity=entity)
	def success(self):
		form=self.get_form()
		form.save()
